package cn.dida.core;

import cn.dida.exception.BizzException;
import cn.dida.model.Sysres;
import cn.dida.model.UserSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
 * 资源树拦截器
 * @author weiwei
 *
 */
public class UserResTreePrepareInterceptor extends HandlerInterceptorAdapter {
    private Log logger = LogFactory.getLog(getClass());


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            return;
        }

        UserSession userSession = (UserSession) request.getAttribute(Constants.USER_SESSION_KEY);

        if (userSession != null) {
            ArrayList<Sysres> resTree = new ArrayList<>();
            if (StringUtils.isNotEmpty(userSession.getResIds())) {
                List<Sysres> userOwnedResNodes = new ArrayList<>();
                List<String> staffResIdList = Arrays.asList(StringUtils.split(userSession.getResIds(), ","));
                for (Sysres resNode : SysresMap.resNodes) {
                    if (staffResIdList.contains(resNode.getId().toString())) {
                        Sysres clone = resNode.clone();
                        userOwnedResNodes.add(clone);
                    }
                }
                resTree.addAll(SysresMap.makeTree(userOwnedResNodes));
                SysresMap.sort(resTree);
            }
            if (modelAndView != null) {
                Map<String, Object> model = modelAndView.getModel();
                model.put("Res_Tree", resTree);
            }
        }
    }

    private void handleUnAuthorized(HttpServletRequest request, HttpServletResponse response) throws IOException {
        throw new BizzException(BizzException.error_code_unauthorized, "您没有权限进行此操作");
    }

}